package com.hongxia.assetsys.controller;

import com.hongxia.assetsys.common.BaseResponse;
import com.hongxia.assetsys.common.ErrorCode;
import com.hongxia.assetsys.common.ResultUtil;
import com.hongxia.assetsys.domain.AssertOrg;
import com.hongxia.assetsys.exception.BusinessException;
import com.hongxia.assetsys.service.AssertOrgService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController()
@RequestMapping("/org")
@RequiresRoles(value = {"asset manager", "admin"}, logical = Logical.OR)
public class OrgController {
    @Autowired
    AssertOrgService orgService;

    @PostMapping
    public BaseResponse<Integer> addOrg(@RequestBody AssertOrg org){
        if(org == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer id = orgService.addOrg(org);
        return ResultUtil.success(id);
    }

    @PutMapping
    public BaseResponse<Integer> updateOrg(@RequestBody AssertOrg org){
        if(org == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer id = org.getId();
        orgService.updateById(org);
        return ResultUtil.success(id);
    }

    @GetMapping("/{id}")
    public BaseResponse<AssertOrg> getOrgById(@PathVariable Integer id){
        if(id < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        AssertOrg org = orgService.getById(id);
        return ResultUtil.success(org);
    }

    @GetMapping("/list")
    public BaseResponse<List<AssertOrg>> getOrgList(){
        List<AssertOrg> orgList = orgService.list();
        return ResultUtil.success(orgList);
    }

    @GetMapping("/search")
    public BaseResponse<List<AssertOrg>> getOrgListLikely(String orgname){
        List<AssertOrg> orgList = orgService.getOrgListLikely(orgname);
        return ResultUtil.success(orgList);
    }

    @GetMapping("/search/fatherorg")
    public BaseResponse<List<AssertOrg>> getOrgListByFatherOrg(String fatherorg){
        List<AssertOrg> orgList = orgService.getOrgListByFatherOrg(fatherorg);
        return ResultUtil.success(orgList);
    }
}
